package com.meixiang.activity.homes.shopping;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.request.BaseRequest;
import com.meixiang.R;
import com.meixiang.adapter.shopping.ShoppingCartExpandableAdapter;
import com.meixiang.dialog.LoadingDialog;
import com.meixiang.entity.shopping.CartStoreEntity;
import com.meixiang.entity.shopping.result.ShowCartResult;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 购物车
 *
 * @author LZRUI
 */
public class ShoppingCartActivity extends BaseActivity implements ShoppingCartExpandableAdapter.OnShoppingCartChangeListener, OnRefreshListener {

    public static final String TAG = "ShoppingCartActivity";

    @Bind(R.id.tv_total_price)
    TextView tvTotalPrice;
    @Bind(R.id.tv_save_money)
    TextView tvSaveMoney;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    @Bind(R.id.swipe_target)
    ExpandableListView eplvGoodsList;
    @Bind(R.id.tv_settle_accounts)
    TextView tvSettleAccounts;
    @Bind(R.id.rl_bottom)
    RelativeLayout rlBottom;

    private ShoppingCartExpandableAdapter adapter;
    private List<CartStoreEntity> cartStoreList;
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_shopping_cart);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        HttpUtils.tagCancelRequest(TAG);
    }

    @Override
    protected void initTitle() {
        setTitle("购物车");
    }

    @Override
    protected void initView() {
        loadingDialog = new LoadingDialog(this);
        mRefresh.setOnRefreshListener(this);
        mRefresh.setLoadingMore(false);
        eplvGoodsList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(view, 1)) {
                        mRefresh.setLoadingMore(true);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        tvTotalPrice.setText(String.format(getString(R.string.price_str), 0));
        tvSaveMoney.setVisibility(View.GONE);
        initListView();
        setOnClickListener();
    }

    @Override
    protected void setData() {
        getCartData(true);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDataChange(String totalPrice, String totalSavePrice) {
        tvTotalPrice.setText(String.format(getString(R.string.price_str), totalPrice));
        if (!TextUtils.isEmpty(totalSavePrice) && TextUtils.isDigitsOnly(totalSavePrice) && Float.valueOf(totalSavePrice) > 0.0f) {
            tvSaveMoney.setVisibility(View.VISIBLE);
            tvSaveMoney.setText(String.format(getResources().getString(R.string.already_save_price), totalSavePrice));
        } else {
            tvSaveMoney.setVisibility(View.GONE);
        }
    }

    @Override
    public void onCartEmpty() {
        rlBottom.setVisibility(View.GONE);
        status.showNoData("购物车里啥都没有，快去选购吧！", "去逛逛", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ShoppingCartActivity.this, ShoppingHomeActivity.class));
            }
        });
    }

    @Override
    public void onCartSelectNull() {
        getCartData(false);
    }

    @Override
    public void onRefresh() {
        getCartData(true);
        tvTotalPrice.setText(String.format(getString(R.string.price_str), 0));
    }

    /**
     * 初始化列表
     */
    private void initListView() {
        adapter = new ShoppingCartExpandableAdapter(this);
        adapter.setOnShoppingCarChangeListener(this); // 设置数据变化监听
        eplvGoodsList.setAdapter(adapter);
        // 去掉组的指示器
        eplvGoodsList.setGroupIndicator(null);
        // 切断ExpandableListView Group的展开和折叠功能
        eplvGoodsList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
    }

    /**
     * 设置监听
     */
    private void setOnClickListener() {
        // 通过监听器关联Activity和Adapter的关系，达到解耦的目的；
        View.OnClickListener onClickListener = adapter.getOnClickListener();
        if (onClickListener != null) {
            tvSettleAccounts.setOnClickListener(onClickListener); // 给结算按钮设置点击事件
        }
    }

    /**
     * 获取购物车数据
     */
    private void getCartData(final boolean showLoadingStatusView) {
        HttpUtils.post(Config.SHOW_CART, TAG, null, new HttpCallBack(ShoppingCartActivity.this) {

            @Override
            public void onBefore(BaseRequest request) {
                if (!Tool.isNetworkAvailable(activity)) {
                    OkHttpUtils.getInstance().cancelTag(ShoppingCartActivity.this);
                    if (status == null) return;
                    status.showNoNewWork(null);
                } else {
                    if (status != null && showLoadingStatusView) {
                        status.showLoading();
                    }else if (!showLoadingStatusView){
                        loadingDialog.show();
                    }
                }
            }

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                ShowCartResult cartResult = AbJsonUtil.fromJson(result.toString(), ShowCartResult.class);
                cartStoreList = cartResult.getStoreList();
                adapter.refreshData(cartStoreList);
                if (cartStoreList != null && !cartStoreList.isEmpty()) {
                    rlBottom.setVisibility(View.VISIBLE);
                    // 打开全部item
                    for (int i = 0; i < cartStoreList.size(); i++) {
                        eplvGoodsList.expandGroup(i);
                    }
                }
            }

            @Override
            public void onError(String code, String message) {

            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                if (mRefresh == null) return;
                mRefresh.setRefreshing(false);
                if (adapter.getGroupCount() == 0) {
                    status.showNoData("购物车里啥都没有，快去选购吧！", "去逛逛", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(ShoppingCartActivity.this, ShoppingHomeActivity.class));
                        }
                    });
                } else {
                    if (status != null && showLoadingStatusView) {
                        status.removeAttachView();
                    }else if (!showLoadingStatusView){
                        loadingDialog.dismiss();
                    }
                }
            }
        });
    }

}
